package com.bang.study.query;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.script.mustache.SearchTemplateRequest;
import org.elasticsearch.script.mustache.SearchTemplateRequestBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: SearchTemplatePageQuery
 * @author: BANG
 * @Date: 2020/01/13 18:24
 * @Version: 1.0
 * @Modified By:
 * @Desc: 搜索模板的功能，java api怎么去调用一个搜索模板
 */
public class SearchTemplatePageQuery {

    public static void main(String[] args) throws UnknownHostException {
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").put("client.transport.sniff", true).build();
        TransportClient client=new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300)
        );

        SearchTemplateRequestBuilder builder = new SearchTemplateRequestBuilder(client);
        Map<String, Object> scriptParams = new HashMap<String, Object>();
        scriptParams.put("from", 0);
        scriptParams.put("size", 2);
        scriptParams.put("brand", "宝马");
        SearchResponse searchResponse = builder.setScript("page_query_by_brand").setScriptParams(scriptParams)
                .setScriptType(ScriptType.FILE)
                .setRequest(new SearchRequest("car_shop").types("sales"))
                .get().getResponse();

        for(SearchHit searchHit : searchResponse.getHits().getHits()) {
            System.out.println(searchHit.getSourceAsString());
        }

        client.close();
    }
}
